import { IncomingMessage, ServerResponse } from "http";
import { GiveHistoryDao } from "../hall_server/dao/GiveHistoryDao";
import { HallServer_SocketMsgHandler } from "../hall_server/HallServer_SocketMsgHandler";
import { Config } from "../src/config/Config";
import { ErrorCode } from "../src/config/ErrorCode";
import { ServerConfig } from "../src/config/ServerConfig";
import DateUtil from "../src/engine/utils/DateUtil";
import { HaoEncrypt } from "../src/engine/utils/HaoEncrypt";
import { Logger } from "../src/engine/utils/Logger";
import { Md5Helper } from "../src/engine/utils/Md5Helper";
import { WebUtil } from "../src/engine/utils/WebUtil";
import { ClubTopDao } from "./dao/ClubTopDao";
import { Club_Freeze_HistoryDao } from "./dao/Club_Freeze_HistoryDao";
import { Club_HistoryDao } from "./dao/Club_HistoryDao";
import { User_Coins_HistoryDao } from "./dao/User_Coins_HistoryDao";
import { User_Gems_HistoryDao } from "./dao/User_Gems_HistoryDao";
import { User_Meilis_HistoryDao } from "./dao/User_Meilis_HistoryDao";
import { User_Spend_DailyDao } from "./dao/User_Spend_DailyDao";
import { LogMethodConfig } from "./LogMethodConfig";
import { LogTest } from "./LogTest";
import { ServerManager } from "../src/server/ServerManager"
import { RoomStatisticsDao } from "./dao/RoomStatisticsDao";
import { ResponseModel } from "../src/model/ResponseModel";
const request = require('request');
const crypto = require("crypto");

const routerMap = {
    updateServerStatus: "/updateServerStatus",
    get_server_info: "/get_server_info"

}

export class LogReqHandler {

    public static instance: LogReqHandler = new LogReqHandler();


    public init(app) {
        for (const key in routerMap) {
            app.use(routerMap[key], this.onBaseRoot.bind(this))
        }
        for (const key in LogMethodConfig.method_type) {
            app.use(LogMethodConfig.method_type[key], this.onBaseRoot.bind(this))
        }
    }

    private onBaseRoot(req, resp) {
        try {
            let ip: string = WebUtil.getIpByExpressReq(req);
            Logger.log("onBaseRoot=req=", ip, req.baseUrl)
            if (req.baseUrl == routerMap.updateServerStatus) {
                ServerConfig.initConfig(ServerConfig.nowServerConfig.nowPort)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.club_in_out_history) {
                Club_HistoryDao.insert_in_out_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.club_freeze_history) {
                Club_Freeze_HistoryDao.insert_freeze_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_club_in_out_history) {
                this.checkBody(ip, req, resp, this.on_get_club_in_out_history.bind(this))
            }
            else if (req.baseUrl == LogMethodConfig.method_type.club_top) {
                ClubTopDao.insertTop(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_club_top) {
                this.checkBody(ip, req, resp, this.on_get_club_top.bind(this))
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_club_top_one) {
                this.checkBody(ip, req, resp, this.on_get_club_top_one.bind(this))
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_club_freeze_history) {
                this.checkBody(ip, req, resp, this.on_get_club_freeze_history.bind(this))
            }
            else if (req.baseUrl == LogMethodConfig.method_type.insert_give_history) {
                GiveHistoryDao.insert_give_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_give_history) {
                this.checkBody(ip, req, resp, this.on_get_give_history.bind(this))
            }
            else if (req.baseUrl == LogMethodConfig.method_type.add_user_spend_daily) {
                User_Spend_DailyDao.add_user_spend_daily(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.add_user_gems_history) {
                User_Gems_HistoryDao.add_user_gems_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.add_user_coins_history) {
                User_Coins_HistoryDao.add_user_coins_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == routerMap.get_server_info) {
                LogTest.instance.leave()
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.add_user_meilis_history) {
                User_Meilis_HistoryDao.add_user_meilis_history(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.add_room_statistics) {
                RoomStatisticsDao.insert(req.body)
                resp.end("success");
            }
            else if (req.baseUrl == LogMethodConfig.method_type.get_club_room_statics) {
                this.checkBody(ip, req, resp, this.on_get_club_room_statics.bind(this))
            }

        } catch (error) {
            Logger.warn("onBaseRoot error", error);
        }
    }

    private checkBody(ip: string, req, resp, callback: Function) {
        if (req.body) {
            try {
                let jsonObj = JSON.parse(req.body);
                let k: string = jsonObj["k"];
                let data: object = jsonObj["data"]
                if (k == Md5Helper.getMd5_encrypt(JSON.stringify(data))) {
                    callback && callback(req, resp, data, ip);
                }
                else {
                    Logger.warn("收到非法Http请求 key", ip, req.body)
                    resp.end();
                }
            } catch (error) {
                Logger.warn("收到非法Http请求body", ip, req.body, error)
                resp.end();
            }
        }
        else {
            resp.end();
        }
    }

    private async on_get_club_in_out_history(req, resp, data: object, ip) {
        let clubid: number = data["clubid"]
        let result: Array<object> = await Club_HistoryDao.get_in_out_history(clubid)
        let obj: object = {
            "code": ErrorCode.Code.Suc,
            "data": result
        }
        resp.end(JSON.stringify(obj));
    }

    private async on_get_club_freeze_history(req, resp, data: object, ip) {
        let clubid: number = data["clubid"]
        let result: Array<object> = await Club_Freeze_HistoryDao.get_history(clubid)
        let obj: object = {
            "code": ErrorCode.Code.Suc,
            "data": result
        }
        resp.end(JSON.stringify(obj));
    }

    private async on_get_club_top(req, resp, data: object, ip) {
        let clubid: number = data["clubid"]
        let topType: number = data["topType"]
        let dateStr: string = data["dateStr"]
        let page_size: number = data["page_size"]
        let cur_page: number = data["cur_page"]
        let result: Array<object> = await ClubTopDao.get_club_top(clubid, topType, dateStr, page_size, cur_page)
        let totalNum: number = await ClubTopDao.get_club_top_totalnum(clubid, dateStr);
        let resultObj: object = {
            "data": result,
            "totalNum": totalNum
        }
        let obj: object = {
            "code": ErrorCode.Code.Suc,
            "data": resultObj
        }
        resp.end(JSON.stringify(obj));
    }

    private async on_get_club_top_one(req, resp, data: object, ip) {
        let clubid: number = data["clubid"]
        let userid: number = data["userid"]
        let dateStr: string = data["dateStr"]
        let result: Array<object> = await ClubTopDao.get_club_top_one(clubid, userid, dateStr)
        let obj: object = {
            "code": ErrorCode.Code.Suc,
            "data": result
        }
        resp.end(JSON.stringify(obj));
    }

    private async on_get_give_history(req, resp, data: object, ip) {
        let sender: number = data["sender"]
        let reciver: number = data["reciver"]
        let page_size: number = data["page_size"]
        let cur_page: number = data["cur_page"]
        let result: Array<object> = await GiveHistoryDao.get_give_history(sender, reciver, cur_page, page_size)
        let totalNum: number = await GiveHistoryDao.get_give_history_totalnum(sender, reciver);
        let resultObj: object = {
            "data": result,
            "totalNum": totalNum
        }
        let obj: object = {
            "code": ErrorCode.Code.Suc,
            "data": resultObj
        }
        resp.end(JSON.stringify(obj));
    }

    private async on_get_club_room_statics(req, resp, data: object, ip) {
        let clubid: number = data["clubid"]
        let time: number = data["time"];
        let startTime: string = DateUtil.formatDateStr(time)
        let endTime: string = DateUtil.formatDateStr(time + Config.OneDay)
        let dataList: Array<object> = await RoomStatisticsDao.get_statistics(clubid, startTime, endTime)
        let respModel: ResponseModel = new ResponseModel()
        respModel.data = dataList.length;
        resp.end(JSON.stringify(respModel));

    }

}